package com.sright.bcard.enterprise.biz.service;

import com.sright.bcard.common.service.share.dto.enterprise.AllEnterpriseDTO;
import com.sright.bcard.common.service.share.dto.page.BetweenDateParamRequest;
import com.sright.bcard.common.service.share.dto.page.PageParamRequest;
import com.sright.bcard.common.service.share.dto.pager.Pager;
import com.sright.bcard.common.service.share.dto.LoginUser;
import com.sright.bcard.common.service.share.dto.request.CreateAccountParam;
import com.sright.bcard.common.service.share.dto.request.TextCheckRequest;
import com.sright.bcard.common.service.share.dto.user.RegisterDTO;
import com.sright.bcard.common.service.share.enums.SourceTypeEnum;
import com.sright.bcard.common.service.share.utils.DataConvertUtils;
import com.sright.bcard.common.service.share.utils.JedisUtil;
import com.sright.bcard.common.service.share.utils.JsonUtil;
import com.sright.bcard.content.dal.dao.UserDAO;
import com.sright.bcard.content.share.service.MessageService;
import com.sright.bcard.content.share.service.TextCheckService;
import com.sright.bcard.enterprise.biz.manager.EnterpriseManager;
import com.sright.bcard.enterprise.dal.dao.EnterpriseDAO;
import com.sright.bcard.enterprise.dal.entity.ext.EnterpriseExtraDO;
import com.sright.bcard.common.service.share.dto.enterprise.EnterpriseDTO;
import com.sright.bcard.common.service.share.dto.enterprise.EnterpriseMemberDTO;
import com.sright.bcard.enterprise.share.request.UpdateEnterpriseParam;
import com.sright.bcard.enterprise.share.service.EnterpriseService;
import com.sright.bcard.user.biz.manager.AuthManager;
import com.sright.common.response.SrightResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.xb.xsdschema.All;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class EnterpriseServiceImpl implements EnterpriseService {

    private final static String APPLY_PUSH_KEY = "ExpireEnterprisePush";

    private final static String APPLY_OPEN_PUSH_KEY = "EnterpriseOpenPush";

    @Autowired
    private JedisUtil jedisUtil;

    @Autowired
    private EnterpriseManager enterpriseManager;

    @Autowired
    private EnterpriseDAO enterpriseDAO;

    @Autowired
    private UserDAO userDAO;

    @Autowired
    AuthManager authManager;

    @Autowired
    MessageService messageService;

    @Autowired
    private TextCheckService textCheckService;

    @Override
    public EnterpriseDTO getEnterpriseDTO(Long enterpriseId) {
        return enterpriseManager.getEnterpriseDTO(enterpriseId);
    }

    @Override
    public SrightResponse getEnterprise(LoginUser loginUser) {
        return SrightResponse.defaultSuccess(enterpriseManager.getEnterprise(loginUser));
    }

    @Override
    public SrightResponse updateEnterpriseInfo(UpdateEnterpriseParam param) {
        return SrightResponse.defaultSuccess(enterpriseManager.updateEnterpriseInfo(param));
    }

    @Override
    public SrightResponse enterpriseInfo(Long enterpriseId) {
        return SrightResponse.defaultSuccess(enterpriseManager.enterpriseInfo(enterpriseId));
    }

    @Override
    public SrightResponse<Pager<EnterpriseMemberDTO>> enterpriseMember(Integer page, Integer pageSize, String keywords, Long enterpriseId) {
        return SrightResponse.defaultSuccess(enterpriseManager.enterpriseMember(page, pageSize, keywords, enterpriseId));
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean confirmApply(EnterpriseDTO enterpriseDTO) throws ParseException {
        TextCheckRequest request = new TextCheckRequest();
        request.setName(enterpriseDTO.getContacts());
        request.setCompany(enterpriseDTO.getName());
        request.setJob(enterpriseDTO.getJob());
        textCheckService.textCheck(request,null, SourceTypeEnum.OPERATE_BACKEND.getValue());
        RegisterDTO registerDTO = new RegisterDTO();
        DataConvertUtils.convertDTO2DO(enterpriseDTO, registerDTO);
        registerDTO.setEnterpriseId(enterpriseDTO.getId());
        registerDTO.setUsername(enterpriseDTO.getMobile());
        registerDTO.setPassword(enterpriseDTO.getMobile());
        authManager.register(registerDTO);
        return messageService.updateOpenStatus(enterpriseDTO.getId(), true);
    }

    @Override
    public Pager<AllEnterpriseDTO> searchEnterpriseByKeyword(String keyword, Integer status, BetweenDateParamRequest betweenDateParamRequest, PageParamRequest request) {
        Date currentDate = new Date();
        Integer count = enterpriseDAO.countOfEnterpriseExtra(keyword, status, betweenDateParamRequest,currentDate);
        List<EnterpriseExtraDO> doList = enterpriseDAO.selectPageOfEnterpriseExtra(keyword, status, betweenDateParamRequest, request,currentDate);
        List<AllEnterpriseDTO> dtoList = new ArrayList<>();
        DataConvertUtils.convertDOList2DTOList(doList, dtoList, AllEnterpriseDTO.class);
        for (AllEnterpriseDTO enterpriseDTO : dtoList) {
            Long bindUserNum = userDAO.selectBindUserNumById(enterpriseDTO.getId());
            Long createUserNum = userDAO.selectCreatedUserNum(enterpriseDTO.getId());
            if (enterpriseDTO.getExpirationAt() != null) {
                if (enterpriseDTO.getExpirationAt().compareTo(new Date()) < 0) {
                    enterpriseDTO.setStatus(2);
                }
            }
            enterpriseDTO.setBindedUserNum(bindUserNum);
            enterpriseDTO.setCreatedUserNum(createUserNum);
        }

        Pager<AllEnterpriseDTO> page = new Pager<>(request.getPageIndex(), request.getPageSize(), count, dtoList);
        return page;
    }

    @Override
    public List<EnterpriseDTO> getEnterpriseList() {
        return enterpriseManager.getEnterpriseList();
    }

    @Override
    public Boolean updateEnterprise(EnterpriseDTO dto) throws ParseException {
        return enterpriseManager.updateEnterprise(dto);
    }

    @Override
    public void pushExpireEnterprise() {
        Boolean lock = jedisUtil.getLock(APPLY_PUSH_KEY, 300000L);
        if(lock) {
            try {
                //获取JobDetail中关联的数据
                 enterpriseManager.pushExpireEnterprise();
                log.info("企业试用到期推送脚本执行成功");
            } catch (Throwable throwable) {
                log.error("企业试用到期推送脚本执行失败；error : {}", throwable);
            } finally {
                jedisUtil.releaseLock(APPLY_PUSH_KEY);
            }
        } else {
            log.info("dint't get lock");
        }

    }

    @Override
    public SrightResponse onStatus(EnterpriseDTO enterpriseDTO) {
        return SrightResponse.defaultSuccess(enterpriseManager.onStatus(enterpriseDTO));
    }

    @Override
    public void pushEnterpriseOpen() {
        Boolean lock = jedisUtil.getLock(APPLY_OPEN_PUSH_KEY, 300000L);
        if(lock) {
            try {
                //获取JobDetail中关联的数据
                enterpriseManager.pushEnterpriseOpen();
                log.info("企业账号开通5天推送脚本执行成功");
            } catch (Throwable throwable) {
                log.error("企业账号开通5天推送脚本执行失败；error : {}", throwable);
            } finally {
                jedisUtil.releaseLock(APPLY_PUSH_KEY);
            }
        } else {
            log.info("dint't get lock");
        }
    }

    @Override
    public void createAccount(CreateAccountParam param) {
        enterpriseManager.createAccount(param);
    }
}
